
/**
 * Jwt工具类
 */
public class JwtUtil {
    //定义过期时间
    public static final long EXPIRE = ;
    //密匙
    private static final String secret="";
    private static final String secretTemp="";
    private static final String subject="";

    /**
     * 生成头部信息
     *
     * @return
     */
    private static Map<String, Object> createHead() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("typ", "JWT");
        map.put("alg", "HS512");
        return map;
    }

    /**
     * 生成token
     * @param
     * @return
     * @throws JsonProcessingException
     */
    /**
     * ss：发行人
     * exp：到期时间
     * sub：主题
     * aud：用户
     * nbf：在此之前不可用
     * iat：发布时间
     * jti：JWT ID用于标识该JWT
     *
     * @return
     * @throws JsonProcessingException
     */
    public static String createToken(Map<String,Object> map) throws JsonProcessingException {
        String token = Jwts.builder().setHeader(createHead())
                .setSubject(subject)
                .claim("id", map.get("id"))
                .claim("mobile", map.get("mobile"))
                .claim("device_sn", map.get("device_sn"))
                .claim("device_mac", map.get("device_mac"))
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, secret).compact();
        return token;
    }

    /**
     * 解密token
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        try {
            final Claims claims = Jwts.parser().setSigningKey(secret).
                    parseClaimsJws(token).getBody();
            return claims;
        } catch (Exception e) {
        }
        return null;

    }

    /**
     * 临时token
     * @param map
     * @return
     * @throws JsonProcessingException
     */
    public static String createTempToken(Map<String,Object> map) throws JsonProcessingException {
        String token = Jwts.builder().setHeader(createHead())
                .setSubject(subject)
                .claim("mobile", map.get("mobile"))
                .claim("device_sn", map.get("device_sn"))
                .claim("device_mac", map.get("device_mac"))
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, secretTemp).compact();
        return token;

    }

    /**
     * 解密临时token
     * @param token
     * @return
     */
    public static Claims checkTempJWT(String token) {
        try {
            final Claims claims = Jwts.parser().setSigningKey(secretTemp).
                    parseClaimsJws(token).getBody();
            return claims;
        } catch (Exception e) {
        }
        return null;

    }


}
